<template>
  <view class="course-detail-container">
    <!-- 顶部标题栏 -->
    <view class="page-header">
      <view class="header-title">课程详情</view>
    </view>

    <!-- 内容区域 -->
    <view class="content-section">
      <!-- 课程基本信息 -->
      <view class="course-header">
        <view class="course-title">{{ pageData.courseName }}</view>
        <view class="course-institution">{{ pageData.companyName }}</view>
        <view class="course-price">
          <text class="price-value"
            >¥{{ (pageData.courseFee / 100).toFixed(2) }}</text
          >
        </view>
      </view>
     
      <!-- 课程详情 -->
      <view class="section-header">
        <view class="section-title">
          <view class="title-decoration"></view>
          <text>课程详情</text>
        </view>
      </view>

      <view class="detail-content">
        <view v-if="pageData.detail" class="detail-text">{{
          pageData.detail
        }}</view>
        <view v-else class="empty-state">
          <text class="empty-text">暂无详情信息</text>
        </view>
      </view>
	   <!-- 课程图片 -->
	   <view class="media-container" v-if="mainImg">
        <image
          :src="globalData.OSS_URL + mainImg"
          mode="widthFix"
          class="course-image"
        />
      </view>

    </view>

    <!-- 底部操作按钮 -->
    <view class="footer-action">
      <button
        class="share-button"
        open-type="share"
        v-if="isTeacher && organId == teacherOrganId"
      >
        <text class="button-text">分享课程</text>
      </button>
      <!-- 学生身份或未登录都显示报名按钮 -->
      <button class="enroll-button" @click="goSignUp" v-else>
        <text class="button-text">立即报名</text>
      </button>
    </view>
  </view>
</template>

<script>
import api from "@/utils/api.js";
import { globalData } from "@/utils/util";
import { getUserInfo } from "@/utils/index";
import { onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app';

export default {
  data() {
    return {
      pageData: {},
      isTeacher: false,
      sharecode: "",
      orderId: "", // 订单id
      mainImg: "",
      organId: "",
      teacherOrganId: "",
	  globalData
    };
  },
  methods: {
    // 获取课程详情
    async getpageDetail(courseId) {
      try {
        await api.organCourseDetail({ courseId }).then((res) => {
          if (res.code != 0) return;
          this.pageData = res.data;
          this.mainImg = res.data.mainImg;
        });
      } catch (error) {
        console.error("请求失败:", error);
      }
    },
    // 获取课程分享code
    async getShareLink(courseId) {
      try {
        await api.getShareLink({ courseId }).then((res) => {
          if (res.code != 0) return;
          this.sharecode = res.data;
        });
      } catch (error) {
        console.error("请求失败:", error);
      }
    },
    // 报名
    async goSignUp() {
      // 检查是否已登录
      const userInfo = await getUserInfo();
      console.log(userInfo, 'userInfo');
      if (!userInfo) {
        // 未登录，跳转到登录页
        uni.navigateTo({
          url: "/pages/login/login",
        });
        return;
      }
      
      // 已登录但没有录入信息
      if (!userInfo.idNo) {
        // 没有录入信息
        uni.navigateTo({
          url: "/pages/myInfo/myInfo",
        });
      } else {
        // 已录入信息
        this.goOrder();
      }
    },
    // 进行下单
    async goOrder() {
      if (uni.getStorageSync("sharecode") || this.sharecode) {
        let sharecode = uni.getStorageSync("sharecode") || this.sharecode;
        await api.bindShareLink({ linkCode: sharecode }).then((res) => {
          if (res.code != 0) return;
          this.goPay(res.data);
        });
      } else {
        await api
          .orderInfoAdd({ skuId: this.pageData.courseId })
          .then((res) => {
            if (res.code != 0) return;
            this.goPay(res.data);
          });
      }
    },
    // 调起支付
    async goPay(orderId) {
      await api.orderPayWXPay({ orderId: orderId }).then((res) => {
        if (res.code != 0) return;
        let { timeStamp, nonceStr, pkInfo, signType, paySign } = res.data;
        uni.requestPayment({
          provider: "wxpay",
          timeStamp,
          nonceStr,
          package: pkInfo,
          signType,
          paySign,
          success: () => {
            uni.showToast({
              title: "支付成功",
              icon: "success",
            });
            setTimeout(() => {
              uni.switchTab({
                url: "/pages/index/index",
              });
            }, 1500);
          },
          fail: (err) => {
            console.error("支付失败", err);
          },
        });
      });
    },
    async getUserInfo() {
      const res = await getUserInfo();

      this.isTeacher = res.isTeacher === 1;
      this.teacherOrganId = res.organId;
      console.log('用户类型:', this.isTeacher ? '教师' : '学生', '用户organId:', this.teacherOrganId, '课程organId:', this.organId);
      
    },
  },
  onShareAppMessage(res) {
    if (res.from === "button") {
      return {
        title: "飞手之家(教练)",
        path:
          "/pages/courseDetail/courseDetail?sharecode=" +
          this.sharecode +
          "&courseId=" +
          this.pageData.courseId,
        imageUrl: "../../static/images/head.jpg",
      };
    } else {
      return {
        title: "飞手之家(个人)",
        path:
          "/pages/courseDetail/courseDetail?courseId=" + this.pageData.courseId,
        imageUrl: "../../static/images/head.jpg",
      };
    }
  },


  onLoad(options) {
    this.courseId = options.courseId;
    this.organId = options.organId;
    this.getUserInfo();
    this.getpageDetail(options.courseId);
    
    // 先判断Storage中是否有用户信息
    const userInfo = uni.getStorageSync("userInfo");
    if (userInfo) {
      this.isTeacher = userInfo.isTeacher === 1;
      this.teacherOrganId = userInfo.organId;
    }
    
    // 如果是老师，获取分享code
    if (this.isTeacher) this.getShareLink(options.courseId);
    // 如果是学生，并且点击链接进来
    if (options.sharecode) {
      uni.setStorageSync("sharecode", options.sharecode);
      uni.setStorageSync("jlSharecourseId", options.courseId);
      this.sharecode = options.sharecode;
    }
    
  },

    // 分享到朋友圈
    onShareTimeline() {
    return {
      title: this.pageData.courseName || '分享一个课程',
      query: `courseId=${this.pageData.courseId}${this.sharecode ? '&sharecode=' + this.sharecode : ''}`,
      imageUrl: this.mainImg ? globalData.OSS_URL + this.mainImg : "../../static/images/head.jpg",
    };
  },

  onShareAppMessage() {
    return {
      title: this.pageData.courseName || '分享一个课程',
      path: `/pages/courseDetail/courseDetail?courseId=${this.pageData.courseId}`,
      imageUrl: this.mainImg ? globalData.OSS_URL + this.mainImg : "../../static/images/head.jpg",
    };
  },

};
</script>

<style lang="scss" scoped>
.course-detail-container {
  background-color: #f6f8fa;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

.page-header {
  background-color: #2cbaff;
  padding: 40rpx 40rpx;
  color: #fff;
  position: relative;
  text-align: center;
}

.header-title {
  font-size: 36rpx;
  font-weight: bold;
}

.content-section {
  width: 92%;
  margin: 30rpx auto;
}

.course-header {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.course-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 16rpx;
}

.course-institution {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 20rpx;
}

.course-price {
  margin-top: 20rpx;
}

.price-value {
  font-size: 40rpx;
  font-weight: bold;
  color: #ff5a5f;
}

.media-container {
  width: 100%;
  margin-top: 30rpx;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  background-color: #fff;
}

.course-image {
  width: 100%;
  display: block;
}

.section-header {
  margin-bottom: 20rpx;
}

.section-title {
  display: flex;
  align-items: center;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.title-decoration {
  width: 8rpx;
  height: 32rpx;
  background-color: #2cbaff;
  border-radius: 4rpx;
  margin-right: 16rpx;
}

.detail-content {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.detail-text {
  font-size: 28rpx;
  line-height: 1.8;
  color: #333;
  text-align: justify;
}

.footer-action {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx 30rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: center;
  z-index: 999;
}

.share-button,
.enroll-button {
  width: 90%;
  height: 90rpx;
  line-height: 90rpx;
  font-size: 32rpx;
  border-radius: 45rpx;
  text-align: center;
  border: none;
}

.share-button {
  background-color: #2cbaff;
  color: #fff;
  box-shadow: 0 6rpx 10rpx rgba(44, 186, 255, 0.2);
}

.enroll-button {
  background-color: #2cbaff;
  color: #fff;
  box-shadow: 0 6rpx 10rpx rgba(44, 186, 255, 0.2);
}

.button-text {
  font-size: 32rpx;
}

// 空状态
.empty-state {
  padding: 60rpx 0;
  text-align: center;
  color: #999;
}

.empty-text {
  font-size: 28rpx;
}
</style>
